<template>
  <n-spin :show="loading">
    <template v-if="!showSuccessResult">
      <div class="ds-title">
        <div class="title-left">
          <div class="avatar"><img :src="accountAvatar" alt="" /></div>
          <div class="meta">
            <div class="row">
              <span class="name">{{ userInfo.idName }}</span>
              <CardViper :cardInfo="userInfo" />
            </div>
            <div v-if="accountBalanceDisplay" class="balance">余额: {{ accountBalanceDisplay }}</div>
          </div>
        </div>
        <div class="title-right">
          <div class="avatar avatar-back" @click="onBack">
            <img :src="employeeAvatar" alt="" />
            <div class="overlay">
              <svg class="exchange-icon" width="22" height="22" viewBox="0 0 24 24">
                <path fill="#fff"
                  d="M4 7h11l-2.5-2.5L14 3l5 5-5 5-1.5-1.5L15 9H4V7zm16 10H9l2.5 2.5L10 21l-5-5 5-5 1.5 1.5L9 15h11v2z" />
              </svg>
            </div>
          </div>
          <div class="meta">
            <div class="name">{{ employeeName }}</div>
            <div v-if="employeeId" class="id">ID: {{ employeeId }}</div>
          </div>
        </div>
      </div>

      <!-- 在 n-spin 内部切换：成功结果 或 礼物列表 -->
      <div class="gift-list">
        <div class="gift-item" v-for="gift in items" :key="gift.name">
          <div class="gift-image">
            <img :src="gift.imageUrl" alt="" v-if="gift.imageUrl" />
          </div>
          <div class="gift-name">{{ gift.name }}</div>
          <div class="gift-price">￥{{ parseFloat(gift.price).toFixed(2) }}</div>
          <div class="ds-button" @click="giveGiftFn(gift)">打赏</div>
        </div>
      </div>
    </template>
    <div v-else class="success-result-container">
      <n-result status="success" title="打赏成功" description="感谢您的用心支持~">
        <template #icon>
          <svg class="heart-icon" width="64" height="64" viewBox="0 0 24 24">
            <path fill="#FF4C66"
              d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 6 3.99 4 6.5 4c1.74 0 3.41.81 4.5 2.09C12.09 4.81 13.76 4 15.5 4 18.01 4 20 6 20 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" />
          </svg>
        </template>
        <template #footer>
          <n-button type="primary" @click="onContinueReward">继续打赏</n-button>
        </template>
      </n-result>
    </div>

    <!-- 二维码弹窗：仅用于支付中显示 -->
    <n-modal v-model:show="qrVisible" :show-mask="false" :closable="false" :auto-focus="false" class="qr-modal">
      <div class="qr-box">
        <div class="qr-title">扫码支付</div>
        <div class="qr-code"><n-qr-code :value="qrText" :size="300" /></div>
        <div class="qr-paytips">
          <img src="@/assets/wechat.svg" alt="" />微信支付
          <img src="@/assets/alipay.svg" alt="" />支付宝
        </div>
        <div class="qr-close" @click="qrVisible = false"></div>
      </div>
    </n-modal>
  </n-spin>
</template>

<script setup lang="ts">
import { useEnvStore } from '@/store'
const envStore = useEnvStore()
const userInfo = computed(() => envStore.userInfo)
const placeInfo = computed(() => envStore.placeInfo)
import { post, get } from '@/utils/common/request'

interface GiftItem {
  name: string
  price: number | string
  imageUrl?: any
  id?: string | number
}

interface AccountInfo {
  name: string
  avatar: string
  balance?: number
  badgeText?: string
}

interface EmployeeInfo {
  name: string
  avatar: string
  id?: string | number
}

const emit = defineEmits<{ (e: 'back'): void }>()

const props = defineProps<{ items: GiftItem[]; account?: AccountInfo; employee?: any }>()

function onBack() {
  emit('back')
}

function formatPrice(p: number | string) {
  if (typeof p === 'number') return `¥${(p / 100).toFixed(2)}`
  return String(p)
}
const accountAvatar = computed(() => props.account?.avatar ?? new URL('@/assets/ava.png', import.meta.url).href)
const accountBalanceDisplay = computed(() => {
  return formatPrice(userInfo.value.cashAccount + userInfo.value.presentAccount)
})

const employeeName = computed(() => props.employee?.name ?? '—')
const employeeAvatar = computed(() => props.employee?.avatar ?? new URL('@/assets/ava.png', import.meta.url).href)
const employeeId = computed(() => props.employee?.id)

// 支付成功结果控制：关闭弹窗并切换到 n-spin 内部成功视图
const showSuccessResult = ref(false)
function handlePaySuccessResult() {
  stopPolling()
  qrVisible.value = false
  showSuccessResult.value = true
}
function onContinueReward() {
  showSuccessResult.value = false
  // 保证弹窗已关闭
  qrVisible.value = false
}

const giveGiftFn = (gift: GiftItem) => {
  loading.value = true
  const price = +gift.price * 100
  const { idNumber, idName, cardId, cardTypeId } = userInfo.value
  const { placeId, areaId, clientId, clientName } = placeInfo.value
  const target = {
    payType: 'AGGREGATE_PAY',
    remark: '',
    orderGoodsList: [
      {
        quantity: 1,
        present: 0,
        discounts: 0,
        specs: '',
        goodsId: gift.id,
        goodsName: gift.name,
        unitPrice: price,
      },
    ],
    totalMoney: price,
    realMoney: price,
    sourceType: 'CLIENT',
    placeId,
    clientId,
    clientName,
    idNumber,
    idName,
    cardId,
    areaId,
    cardTypeId,
    createrName: employeeName.value,
    creater: employeeId.value,
  }
  post('/marketing-server/client/giftRewarding/createGiftRewardingOrder', target)
    .then((res: any) => {
      const payUrl = res?.data?.obj?.payUrl ?? res?.data?.payUrl ?? ''
      qrText.value = String(payUrl)
      qrVisible.value = true
      const orderId = res?.data?.obj?.orderId
      if (orderId) startPolling(orderId)
    })
    .catch((e: any) => {
      console.error('createGiftRewardingOrder error', e)
    })
    .finally(() => {
      loading.value = false
    })
}
const loading = ref(false)
const qrVisible = ref(false)
const qrText = ref('')

let pollTimer: any = null
let pollElapsed = 0
const pollLimitSeconds = 60 * 5

function stopPolling() {
  if (pollTimer) {
    clearInterval(pollTimer)
    pollTimer = null
  }
  pollElapsed = 0
}

function startPolling(orderId: string | number) {
  stopPolling()
  pollElapsed = 0
  pollTimer = setInterval(async () => {
    if (pollElapsed >= pollLimitSeconds) {
      console.warn('订单超过5分钟未支付，窗口即将关闭！')
      stopPolling()
      qrVisible.value = false
      return
    }
    try {
      const res: any = await get('/marketing-server/client/orders/queryPaymentStatus', { params: { orderId } })
      if (res?.code === 100000) {
        const status = res?.data?.obj?.status
        if (status == 1) {
          // 支付成功
          handlePaySuccessResult()
        } else if (status == 3 || status == 4) {
          // 库存不足或退款
          handlePaySuccessResult()
          qrVisible.value = false
        }
      }
    } catch (e) {
      console.error('queryPaymentStatus error', e)
    }
    pollElapsed += 5
  }, 5000)
}

watch(qrVisible, (visible) => {
  if (!visible) stopPolling()
})

onUnmounted(() => {
  stopPolling()
})
</script>

<style scoped lang="scss">
.ds-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #000000;
  margin-bottom: 20px;
  background: url('@/assets/dsry.png') no-repeat center center;
  background-size: 100% 100%;
  height: 88px;
  margin: 15px auto;
  padding: 0 24px;
  width: calc(100% - 60px);
}

.title-left,
.title-right {
  display: flex;
  align-items: center;
}

.avatar {
  position: relative;
  width: 56px;
  height: 56px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 12px;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* hover 遮罩与回退图标 */
.avatar-back {
  cursor: pointer;
}

.avatar-back .overlay {
  position: absolute;
  inset: 0;
  background: rgba(0, 0, 0, 0.2);
  display: grid;
  place-items: center;
  opacity: 0;
  transition: opacity .2s ease;
}

.avatar-back:hover .overlay {
  opacity: 1;
}

.meta {
  display: flex;
  flex-direction: column;
}

.row {
  display: flex;
  align-items: center;
}

.name {
  font-size: 18px;
  font-weight: 700;
  color: #333;
  margin-right: 8px;
}

.badge {
  font-size: 12px;
  color: #fff;
  background: #ff8c00;
  border-radius: 12px;
  padding: 2px 8px;
}

.balance {
  margin-top: 4px;
  font-size: 14px;
  color: #ff4d4f;
}

.id {
  margin-top: 4px;
  font-size: 14px;
  color: #555;
}

/* 容器：一行四个，自动换行 */
.gift-list {
  display: grid;
  grid-template-columns: repeat(4, 160px);
  gap: 20px;
  padding: 0 20px;
  justify-content: center;
}

/* item 的大小与 hover 效果与员工页保持一致 */
.gift-item {
  width: 160px;
  height: 200px;
  border: 2px solid transparent;
  transition: background 0.25s ease, border-color 0.25s ease, box-shadow 0.25s ease;
  background: #FAFAFA;
  border-radius: 16px;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #000000;
  font-weight: bold;
  padding-top: 5px;
}

.gift-item:hover {
  border-color: #DA2B25;
  background: linear-gradient(to bottom, #FFD4D3 0%, #FFFFFF 20%, #FFFFFF 100%);
}

/* 礼物图片占位 */
.gift-image {
  width: 80px;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 12px;
}

.gift-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

/* 价格与名称样式 */
.gift-name {
  font-size: 15px;
  font-weight: bold;
}

.gift-price {
  margin-top: 6px;
  font-size: 14px;
  color: #333;
}

/* 打赏按钮风格与原页面一致 */
.ds-button {
  background-image: url('@/assets/ds_button1.png');
  background-size: 100% 100%;
  width: 144px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  color: #fff;
  font-size: 14px;
  font-weight: bold;
  border-radius: 15px;
  margin-top: 10px;
}

/* QR modal styles */
.qr-modal {
  display: grid;
  place-items: center;
}

.qr-box {
  width: 400px;
  background: #fff;
  border-radius: 6px;
  padding: 10px;
  position: relative;
}

.qr-title {
  font-size: 20px;
  font-weight: 700;
  text-align: center;
  margin-bottom: 12px;
  color: #333;
}

.qr-code {
  display: flex;
  justify-content: center;
  margin: 10px 0 12px;
}

.qr-paytips {
  display: flex;
  margin-top: 30px;
  justify-content: center;
  align-items: center;
  gap: 14px;
  color: #666;
  font-size: 14px;
}

.qr-close {
  position: absolute;
  right: 12px;
  top: 12px;
  width: 24px;
  height: 24px;
  background: url('@/assets/gb2.png') no-repeat center/cover;
  cursor: pointer;
}

.heart-icon {
  filter: drop-shadow(0 2px 6px rgba(0, 0, 0, 0.2));
}

.success-result-container {
  padding: 20% 0;
}
</style>